<template>
  <div class="form-container">
    <el-form
      :model="formState.ruleForm"
      :rules="formState.rules"
      ref="formRef"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="楼号" prop="name">
        <el-input v-model="formState.ruleForm.name" />
      </el-form-item>

      <el-form-item label="学院" prop="introduction">
        <el-input v-model="formState.ruleForm.introduction" />
      </el-form-item>

      <el-form-item label="管理员" prop="adminId">
        <el-select v-model="formState.ruleForm.adminId" placeholder="请选择管理员">
          <template v-if="dormitoryAdminList.length > 0">
            <el-option
              v-for="item in dormitoryAdminList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </template>
          <template v-else>
            <el-empty description="暂无宿管数据" />
          </template>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm">立即创建</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { reactive, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { buildingApi, dormitoryAdminApi } from '@/api/buildings'

export default {
  setup() {
    const router = useRouter()
    const formRef = ref(null)
    const dormitoryAdminList = ref([])

    const formState = reactive({
      ruleForm: {
        name: '',
        introduction: '',
        adminId: ''
      },
      rules: {
        name: [{ required: true, message: '请输入楼号', trigger: 'blur' }],
        introduction: [{ required: true, message: '请输入学院', trigger: 'blur' }],
        adminId: [{ required: true, message: '请选择管理员', trigger: 'change' }]
      }
    })

    const getDormitoryAdminList = async () => {
      try {
        const res = await dormitoryAdminApi.getList()
        console.log('宿管接口响应数据:', res)

        // 根据接口实际结构设置值 ↓↓↓
        if (res.code === 0) {
          dormitoryAdminList.value = res.data?.data || res.data || []
        } else {
          ElMessage.error(res.message || '获取管理员列表失败')
        }
      } catch (error) {
        ElMessage.error('获取管理员列表失败: ' + (error.message || error))
        console.error('获取管理员列表错误:', error)
      }
    }

    const submitForm = () => {
      formRef.value.validate(async (valid) => {
        if (valid) {
          try {
            const res = await buildingApi.saveBuilding(formState.ruleForm)
            if (res.code === 0) {
              ElMessageBox.alert(`${formState.ruleForm.name} 添加成功`, '提示', {
                confirmButtonText: '确定',
                callback: () => {
                  router.push('/buildingManager')
                }
              })
            } else {
              ElMessage.error(res.message || '添加失败')
            }
          } catch (error) {
            ElMessage.error('添加失败: ' + (error.response?.data?.message || error.message))
            console.error('添加楼宇错误:', error)
          }
        }
      })
    }

    const resetForm = () => {
      formRef.value.resetFields()
    }

    onMounted(() => {
      getDormitoryAdminList()
    })

    return {
      formRef,
      formState,
      dormitoryAdminList,
      submitForm,
      resetForm
    }
  }
}
</script>

<style scoped>
.form-container {
  margin: 60px auto;
  width: 500px;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>
